package com.example.sevicedemo

import android.app.*
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat

class ForegroundService : Service() {

    private val channelId = "FloatWindowService"
    private val channelName = "计时服务"


    override fun onCreate() {
        super.onCreate()
        addForegroundNotification()
    }


    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val time = intent?.getIntExtra("time", 0)
        println("ForegroundService.onStartCommand time=$time")
        return super.onStartCommand(intent, flags, startId)
    }



    override fun onBind(intent: Intent): IBinder {
        TODO("Return the communication channel to the service.")
    }

    private fun addForegroundNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel = NotificationChannel(
                channelId,
                channelName,
                NotificationManager.IMPORTANCE_HIGH
            )
            notificationChannel.description = "计时服务"
            notificationChannel.setShowBadge(false)
            notificationChannel.lockscreenVisibility =
                Notification.VISIBILITY_PUBLIC //设置锁屏可见 VISIBILITY_PUBLIC=可见
            val manager = getSystemService(
                NotificationManager::class.java
            )
            manager.createNotificationChannel(notificationChannel)
        }
        val priority = NotificationCompat.Builder(applicationContext, channelId)
            .setSmallIcon(R.mipmap.ic_launcher)
            // .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher))
            .setContentTitle("计时服务")
            .setWhen(System.currentTimeMillis())
            .setPriority(NotificationCompat.PRIORITY_HIGH)
        val launchIntent = Intent(this, MainActivity::class.java)
        val mPendingIntent = PendingIntent.getActivity(
            applicationContext,
            0,
            launchIntent,
            PendingIntent.FLAG_UPDATE_CURRENT
        )
        val mNotification = priority.setContentIntent(mPendingIntent).setAutoCancel(false).build()
        startForeground(1, mNotification)
    }

}